<template>
  <div class="app-container">

    <div style="margin-bottom: 20px;">
      <el-button type="primary" icon="Search" @click="getList('1')">获取最新数据</el-button>
      <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      <el-tag v-if="!userStore.isMobile" type="primary" size="large"
        style="margin-left: 20px;">提示:如果有标黄的数据，该条出库单可能出现以下情况：1.销售单价异常 2.销售总金额异常
        3.未实际出库(出库数量为负) 4.成本单价跨批次 请关注</el-tag>
    </div>

    <!-- 搜索框 -->
    <el-input v-model="searchKeyword" placeholder="支持输入出库数量、设备全称、简称、型号、参数搜索" clearable :style="{
      width: userStore.isMobile ? '100%' : '400px',
      marginBottom: userStore.isMobile ? '10px' : '15px'
    }" :size="userStore.isMobile ? 'large' : 'default'" />
    <el-table :max-height="50 + 'vh'" :row-class-name="tableRowClassName" style="overflow: auto;max-height: 50vh;"
      :summary-method="getSummaries" show-summary border v-loading="loading" element-loading-text="成本计算中..."
      :data="filteredSaleList" @selection-change="handleSelectionChange">
      <el-table-column label="出库日期" align="center" prop="saleDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="100" align="center" prop="amount" />
      <!-- <el-table-column label="成本单价" width="200" align="center" prop="costPrice" /> -->
      <el-table-column v-if="viewCost" label="成本单价" width="300" align="left">
        <template #default="scope">
          <el-select :disabled="!(userStore.name == 'wuzg')" @change="costChange(scope.row)"
            v-model="scope.row.costPrice" placeholder="Select" style="width: 200px">
            <el-option v-for="item in scope.row.costList" :key="item" :label="item" :value="item" />
          </el-select>
          <el-button v-if="scope.row.logList != null" link type="danger"
            @click="historyCost(scope.row.logList)">修改记录</el-button>
        </template>
      </el-table-column>
      <el-table-column v-if="viewCost" label="成本合计(￥)" align="center" show-overflow-tooltip width="120"
        prop="costTotal" />
      <el-table-column label="销售单价(￥)" align="center" show-overflow-tooltip width="120" prop="price" />
      <el-table-column label="销售总金额(￥)" show-overflow-tooltip width="120" align="center" prop="total" />
      <el-table-column v-if="viewCost" label="毛利(￥)" show-overflow-tooltip width="120" align="center" prop="profit" />
      <!-- <el-table-column v-if="viewCost" label="毛利率(%)" show-overflow-tooltip width="120" align="center"
        prop="profitRatio" /> -->
      <el-table-column v-if="viewCost" label="毛利率(%)" show-overflow-tooltip width="120" align="center">
        <template #default="scope">
          {{
            formatProfitRatio(scope.row.profitRatio)
          }}
        </template>
      </el-table-column>
      <el-table-column label="设备全称" width="220" show-overflow-tooltip align="center" prop="fullName" />
      <el-table-column label="设备简称" show-overflow-tooltip width="220" align="center" prop="name" />
      <el-table-column label="设备编号" show-overflow-tooltip align="center" prop="modal" />
      <el-table-column label="设备参数" show-overflow-tooltip align="center" prop="param" />
      <el-table-column label="管家婆项目" fixed="bottom" show-overflow-tooltip width="220" align="center"
        prop="companyName" />


    </el-table>

    <el-divider style="font-size: 16px; font-weight: bold;">收款信息</el-divider>

    <div :style="userStore.isMobile ? 'width: 100%; margin-top: 10px;' : 'flex: 0 0 auto; margin-right: 80px;'">
      <div :style="userStore.isMobile ? 'display: flex; flex-direction: column; gap: 8px;' : 'display: inline;'">
        <div :style="userStore.isMobile ? 'display: flex; align-items: center;' : 'display: inline;'">
          应收金额：
          <el-tag size="large" type="primary" style="font-size: 14px; font-weight: bold; margin-left: 4px;">
            {{ amountInfo.should }}
          </el-tag>
        </div>
        <div :style="userStore.isMobile ? 'display: flex; align-items: center;' : 'display: inline;'">
          实收金额：
          <el-tag size="large" type="success" style="font-size: 14px; font-weight: bold; margin-left: 4px;">
            {{ amountInfo.actual }}
          </el-tag>
        </div>
        <div :style="userStore.isMobile ? 'display: flex; align-items: center;' : 'display: inline;'">
          管家婆应收金额：
          <el-tag size="large" type="warning" style="font-size: 14px; font-weight: bold; margin-left: 4px;">
            {{ amountInfo.gjpShould }}
          </el-tag>
        </div>
        <div :style="userStore.isMobile ? 'display: flex; align-items: center;margin-bottom:10px' : 'display: inline;'">
          待收金额：
          <el-tag size="large" type="danger" style="font-size: 14px; font-weight: bold; margin-left: 4px;">
            {{ amountInfo.remaining }}
          </el-tag>
        </div>
      </div>
    </div>

    <el-table :summary-method="getPaySummary" show-summary border :data="payList" style="margin-top: 20px;">
      <el-table-column label="付款公司" align="center" prop="company" />
      <el-table-column label="合同签订金额" align="center" width="120" show-overflow-tooltip prop="totalAmount" />
      <el-table-column label="结算金额" align="center" width="120" show-overflow-tooltip prop="settlementAmount" />
      <!-- <el-table-column label="付款百分比" align="center" prop="percentage" /> -->
      <!-- <el-table-column label="金额" align="center" prop="amount" /> -->
      <!-- <el-table-column label="附件" align="center" prop="files" /> -->
      <el-table-column label="备注" width="220" show-overflow-tooltip align="center" prop="remark" />
      <el-table-column label="发票编号" align="center" width="220" show-overflow-tooltip prop="payNo" />
      <el-table-column label="财务实收金额" align="center" width="120" show-overflow-tooltip prop="receivedAmount" />
      <el-table-column label="收到期票/承兑/保函" align="center" width="120" show-overflow-tooltip prop="promissoryNote" />
      <el-table-column label="期票/承兑/保函到期时间" align="center" prop="promissoryEndDate" />
      <el-table-column label="财务实收百分比(%)" align="center" prop="receivedPercentage" />
      <el-table-column label="附件" align="center" show-overflow-tooltip width="200" prop="fileName">
        <template #default="scope">
          <el-link type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</el-link>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作员" align="center" prop="operator" /> -->
      <!-- <el-table-column label="操作时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column> -->


    </el-table>

    <!-- <pagination style="margin-right: 0px; float: right;" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" /> -->

    <!-- 添加或修改销售对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="saleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="货物id" prop="goodsId">
          <el-input v-model="form.goodsId" placeholder="请输入货物id" />
        </el-form-item>
        <el-form-item label="出售单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入出售单价" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
        <el-form-item label="最后登录IP" prop="loginIp">
          <el-input v-model="form.loginIp" placeholder="请输入最后登录IP" />
        </el-form-item>
        <el-form-item label="最后登录时间" prop="loginDate">
          <el-date-picker clearable v-model="form.loginDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择最后登录时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="数量" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="出库日期" prop="saleDate">
          <el-date-picker clearable v-model="form.saleDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择出库日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="管家婆项目id" prop="housekeeperProject">
          <el-input v-model="form.housekeeperProject" placeholder="请输入管家婆项目id" />
        </el-form-item>
        <el-form-item label="毛利 销售总金额减去成本合计" prop="profit">
          <el-input v-model="form.profit" placeholder="请输入毛利 销售总金额减去成本合计" />
        </el-form-item>
        <el-form-item label="销售总金额" prop="total">
          <el-input v-model="form.total" placeholder="请输入销售总金额" />
        </el-form-item>
        <el-form-item label="成本合计" prop="costTotal">
          <el-input v-model="form.costTotal" placeholder="请输入成本合计" />
        </el-form-item>
        <el-form-item label="成本单价" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入成本单价" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <el-drawer v-model="costDrawer" title="成本修改记录" :with-header="false" size="40%">
    <el-table :data="logList" border>
      <el-table-column label="序号" type="index" width="70" align="center" />
      <el-table-column label="数量" align="center">
        <template #default="scope">
          <span>{{ -scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原成本" align="center" prop="oldCost" />
      <el-table-column label="新成本" align="center" prop="newCost" />
      <el-table-column label="修改人" align="center" prop="operator" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>

  </el-drawer>

</template>

<script setup name="Sale">
import { listSale, getSale, delSale, addSale, updateSale, gjpListSale, gjpAllListSale, exportData, viewCostPermisson } from "@/api/project/sale";
import { listFee, getFee, delFee, addFee, updateFee, listFeeReceive } from "@/api/project/fee";
import { getStepList, getAmountInfo, listPay } from "@/api/project/project";
import { ref } from "vue";
import useUserStore from '@/store/modules/user'
import { listSaleLog, addSaleLog, getSaleLog } from "@/api/project/projectSaleLog";

const costDrawer = ref(false)
const userStore = useUserStore()
const { proxy } = getCurrentInstance();
const payList = ref([]);
const costingList = ref([]);
const saleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const props = defineProps({
  datas: {
    type: Object, // 指定类型为对象
    required: true, // 是否必填
  },
  column: {
    type: Number, // 指定类型为数字
    default: 3, // 设置默认值为 3
  },
  sizes: {
    default: 'default',
  },
  personList: {
    default: [],
  },
  // payList: {
  //   default: [],
  // },
  attachmentList: {
    default: [],
  },
  implementList: {
    default: [],
  },
  warrantyList: {
    default: [],
  },
  accountingList: {
    default: [],
  },

  isView: {
    default: false,
  },

});

//改变的时候往日志表中插入数据
function costChange(row) {
  addSaleLog(row).then(response => {
    proxy.$modal.msgSuccess("成本单价修改成功");
    //重新计算
    getList('1')
  });
}

const logList = ref([])

function historyCost(list) {
  logList.value = list
  costDrawer.value = true

}




const viewCost = ref(false)
const { datas, column, sizes, personList, attachmentList, implementList, accountingList, warrantyList, isView } = toRefs(props);
// 格式化函数：统一处理字符串和数字
const formatProfitRatio = (value) => {
  const num = parseFloat(value)
  return isNaN(num) || num < 0 ? '-' : num.toFixed(2)
}
const data = reactive({
  form: {},
  amountInfo: {
    should: null,
    actual: null,
    remaining: null,
    gjpShould: null,
    same: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    goodsId: null,
    price: null,
    loginIp: null,
    loginDate: null,
    amount: null,
    saleDate: null,
    housekeeperProject: null,
    profit: null,
    total: null,
    costTotal: null,
    costPrice: null,
    refresh: "0"
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);
const { amountInfo } = toRefs(data);
// 行样式方法
const tableRowClassName = ({ row }) => {
  return row.status == "1" ? 'warning-row' : '';
};


const searchKeyword = ref('');


// 计算属性过滤数据
const filteredSaleList = computed(() => {
  const keyword = searchKeyword.value.trim().toLowerCase();
  if (!keyword) {
    return saleList.value;
  }

  return saleList.value.filter(item =>
    [item.fullName, item.name, item.modal, item.param, item.amount].some(field =>
      field != null && String(field).toLowerCase().includes(keyword)
    )
  );


});

/** 查询销售列表 */
function getList(type) {
  loading.value = true;
  queryParams.value.housekeeperProject = datas.value.housekeeperProject
  queryParams.value.projectNo = datas.value.projectNo
  if (!queryParams.value.housekeeperProject) {
    proxy.$modal.msgError("未关联管家婆项目,请先关联");
    loading.value = false;
    return
  }
  queryParams.value.refresh = type
  gjpListSale(queryParams.value).then(response => {
    console.log("出库单数据", response);
    saleList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
  }).finally(() => {
    loading.value = false;
  });


  let param = {
    projectNo: datas.value.projectNo,
  }
  // queryParams.value.refresh = type
  console.log("费用汇总", queryParams.value);
  listFeeReceive(queryParams.value).then(response => {
    costingList.value = response.data;
  });



  getAmountInfo(datas.value.projectNo).then((response) => {
    // getAmountInfo.value = response.data;
    console.log("金额信息", response);

    nextTick(() => {
      amountInfo.value.should = response.data.should
      amountInfo.value.actual = response.data.actual
      amountInfo.value.remaining = response.data.remaining
      amountInfo.value.gjpShould = response.data.gjpShould
      amountInfo.value.same = response.data.same
    });
  });

  let params = {
    projectNo: datas.value.projectNo
  }


  //付款信息
  listPay(params).then((response) => {
    payList.value = response.data;
  });



}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    goodsId: null,
    price: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    loginIp: null,
    loginDate: null,
    amount: null,
    saleDate: null,
    housekeeperProject: null,
    profit: null,
    total: null,
    costTotal: null,
    costPrice: null
  };
  proxy.resetForm("saleRef");
}

function getPaySummary(param) {
  const { columns, data } = param;

  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const key = column.property;
    const validKeys = [
      'receivedAmount',
      'receivedPercentage',
      'promissoryNote'
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList("0");
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加销售";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSale(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改销售";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["saleRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSale(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList("0");
        });
      } else {
        addSale(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList("0");
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除销售编号为"' + _ids + '"的数据项？').then(function () {
    return delSale(_ids);
  }).then(() => {
    getList("0");
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  queryParams.value.housekeeperProject = datas.value.housekeeperProject
  queryParams.value.projectNo = datas.value.projectNo
  queryParams.value.refresh = null
  proxy.download('project/sale/export', {
    ...queryParams.value
  }, `出库单数据_${new Date().getTime()}.xlsx`)


}


function getSummariesback(param) {
  const { columns, data } = param
  console.log("计算12312312", data);
  let filteredData = data.filter(item => item.name !== '已开增票');
  const sums = []
  columns.forEach((column, index) => {

    if (index === 0) {
      sums[index] = `合计（共 ${data.length} 条）`;
      return
    }

    const prop = column.property

    // 需要统计的列及其格式化方式
    const statsConfig = {
      amount: { format: 'int' },    // 数量列显示整数
      costTotal: { format: 'float' }, // 成本合计保留2位小数
      total: { format: 'float' },    // 销售总金额保留2位小数
      profit: { format: 'float' }    // 毛利保留2位小数
    }

    if (statsConfig[prop]) {
      const values = filteredData.map(item => Number(item[prop]))
      if (!values.every(value => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)

        // 根据配置格式化结果
        sums[index] = statsConfig[prop].format === 'int'
          ? Math.round(sum)
          : sum.toFixed(2)

        sums[index] = sums[index]


      } else {
        sums[index] = 'N/A'
      }
    } else {
      sums[index] = ''
    }
  })

  return sums
}


function getSummaries(param) {
  const { columns, data } = param
  console.log("计算12312312", data)
  let filteredData = data.filter(item => item.name !== '已开增票')
  const sums = []

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = `合计（共 ${data.length} 条）`
      return
    }

    const prop = column.property

    // 需要统计的列及其格式化方式
    const statsConfig = {
      amount: { format: 'float' },     // 数量列现在也允许小数
      costTotal: { format: 'float' },  // 成本合计保留2位小数
      total: { format: 'float' },      // 销售总金额保留2位小数
      profit: { format: 'float' }      // 毛利保留2位小数
    }

    if (statsConfig[prop]) {
      const values = filteredData.map(item => Number(item[prop]))
      if (!values.every(value => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)

        // 根据配置格式化结果
        if (statsConfig[prop].format === 'float') {
          sums[index] = parseFloat(sum.toFixed(2)) // 或者直接 sum.toFixed(2) 如果需要字符串形式
        } else {
          sums[index] = Math.round(sum)
        }

      } else {
        sums[index] = 'N/A'
      }
    } else {
      sums[index] = ''
    }
  })

  return sums
}

function getViewCostPermisson() {
  viewCostPermisson(null).then(response => {
    console.log("看成本的权限", response);
    viewCost.value = response
  }).finally(() => {
  });
}

onMounted(() => {
  getViewCostPermisson()
  getList("0");
})
</script>

<style scoped>
/* 确保合计行固定在底部 */
.fixed-summary-table .el-table__footer-wrapper {
  position: sticky;
  bottom: 0;
  z-index: 2;
  background: white;
}

/* 可选：为固定列添加阴影效果 */
.fixed-summary-table .el-table__fixed-right,
.fixed-summary-table .el-table__fixed {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.08);
}

:deep(.el-table .warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

/* 悬停效果 */
:deep(.el-table .warning-row:hover td) {
  --el-table-tr-bg-color: var(--el-color-warning-light-8);
  background-color: var(--el-table-tr-bg-color);
}

/* 如果需要更醒目的边框样式 */
:deep(.el-table .warning-row td) {
  border-bottom: 1px solid var(--el-color-warning-light-5);
  border-top: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .warning-row td:first-child) {
  border-left: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .warning-row td:last-child) {
  border-right: 1px solid var(--el-color-warning-light-5);
}

.line-break {
  white-space: pre-line;
  /* 可选添加最小高度保持行间距 */
  min-height: 40px;
}
</style>
